<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="多线程,ajax,selenium,tesseract图片识别,">










<meta name="description" content="python爬虫进阶">
<meta name="keywords" content="多线程,ajax,selenium,tesseract图片识别">
<meta property="og:type" content="article">
<meta property="og:title" content="Python爬虫（4）">
<meta property="og:url" content="http://Anzusen.com/2019/07/14/Python爬虫（4）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="python爬虫进阶">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/tesseract_install.png">
<meta property="og:updated_time" content="2020-04-06T13:24:57.157Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python爬虫（4）">
<meta name="twitter:description" content="python爬虫进阶">
<meta name="twitter:image" content="http://anzusen.com/image/tesseract_install.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/07/14/Python爬虫（4）/">





  <title>Python爬虫（4） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/07/14/Python爬虫（4）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python爬虫（4）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-14T18:37:02+08:00">
                2019-07-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python爬虫/" itemprop="url" rel="index">
                    <span itemprop="name">Python爬虫</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/07/14/Python爬虫（4）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/07/14/Python爬虫（4）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="python爬虫进阶"><a href="#python爬虫进阶" class="headerlink" title="python爬虫进阶"></a>python爬虫进阶</h1><a id="more"></a>
<h2 id="多线程"><a href="#多线程" class="headerlink" title="多线程"></a>多线程</h2><h3 id="多线程介绍"><a href="#多线程介绍" class="headerlink" title="多线程介绍"></a>多线程介绍</h3><p>  多线程是为了同步完成多项任务,通过提高资源使用效率来提高系统的效率。线程是在同一时间需要完成多项任务的时候实现的。最简单的比喻多线程就像火车的每一节车厢,而进程则是火车。车厢离开火车是无法跑动的，同理火车也可以有多节车厢。多线程的出现就是为了提高效率。同时它的出现也带来了-些问题。</p>
<h3 id="threading模块"><a href="#threading模块" class="headerlink" title="threading模块"></a>threading模块</h3><p>  threading模块是python中专门提供用来做多线程编程的模块。threading 模块中最常用的类是Thread 。threading的一些功能函数有：</p>
<ul>
<li>查看线程数:使用threading . enumerate()函数便可以看到当前线程的数量。</li>
<li>查看当前线程的名字:使用threading.current _thread() 可以看到当前线程的信息。</li>
</ul>
<p>例示代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">coding</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>):</span><br><span class="line">        print(<span class="string">'正在写代码%s'</span>%threading.current_thread())</span><br><span class="line">        time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">drawing</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>):</span><br><span class="line">        print(<span class="string">'正在画图%s'</span> % threading.current_thread())</span><br><span class="line">        time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    t1 = threading.Thread(target=coding)</span><br><span class="line">    t2 = threading.Thread(target=drawing)</span><br><span class="line"></span><br><span class="line">    t1.start()</span><br><span class="line">    t2.start()</span><br><span class="line"></span><br><span class="line">    print(threading.enumerate())</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure></p>
<p>运行结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">正在写代码&lt;Thread(Thread-1, started 1648)&gt;</span><br><span class="line">正在画图&lt;Thread(Thread-2, started 10252)&gt;[&lt;_MainThread(MainThread, started 13940)&gt;, &lt;Thread(Thread-1, started 1648)&gt;, &lt;Thread(Thread-2, started 10252)&gt;]</span><br><span class="line"></span><br><span class="line">正在写代码&lt;Thread(Thread-1, started 1648)&gt;正在画图&lt;Thread(Thread-2, started 10252)&gt;</span><br><span class="line"></span><br><span class="line">正在画图&lt;Thread(Thread-2, started 10252)&gt;</span><br><span class="line">正在写代码&lt;Thread(Thread-1, started 1648)&gt;</span><br><span class="line"></span><br><span class="line">Process finished with exit code 0</span><br></pre></td></tr></table></figure></p>
<p>由运行结果可看出：总共有三个线程，两个子线程执行先后顺序是不固定的。</p>
<h3 id="Thread类"><a href="#Thread类" class="headerlink" title="Thread类:"></a>Thread类:</h3><p>  为了让线程代码更好的封装。可以使用thdeading 模块下的Thread类，继承自这个类，然后实现run 方法，线程就会自动运行run方法中的代码。例示代码如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="comment"># 继承自threading.Thread</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CodingThread</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span><span class="comment"># run方法</span></span><br><span class="line">        <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>):</span><br><span class="line">            print(<span class="string">'正在写代码%s'</span> % threading.current_thread())</span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DrawingThread</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>):</span><br><span class="line">            print(<span class="string">'正在画图%s'</span> % threading.current_thread())</span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    t1 = CodingThread()</span><br><span class="line">    t2 = DrawingThread()</span><br><span class="line"></span><br><span class="line">    t1.start()</span><br><span class="line">    t2.start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h4 id="多线程共享全局变量问题及解决办法：锁机制"><a href="#多线程共享全局变量问题及解决办法：锁机制" class="headerlink" title="多线程共享全局变量问题及解决办法：锁机制"></a>多线程共享全局变量问题及解决办法：锁机制</h4><p>  多线程都是在同一个进程中运行的。因此在进程中的全局变量所有线程都是可共享的。这就造成了一个问题，因为线程执行的顺序是无序的。全局变量变换也是无规则的，有可能会造成数据错误。示例代码如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line">VALUE = <span class="number">0</span> <span class="comment">#全局变量</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># gLock = threading.Lock() # 定义一个锁对象</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_value</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">global</span> VALUE <span class="comment"># 为了使函数体内可以访问这个全局</span></span><br><span class="line">    <span class="comment"># gLock.acquire() #上锁 # 其他线程等待</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">10000000</span>):</span><br><span class="line">        VALUE += <span class="number">1</span></span><br><span class="line">    <span class="comment"># gLock.release() # 去锁</span></span><br><span class="line">    print(<span class="string">'value：%d'</span>%VALUE)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">2</span>):</span><br><span class="line">        t = threading.Thread(target=add_value)</span><br><span class="line">        t.start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">没上锁前：</span><br><span class="line">value：11535753</span><br><span class="line">value：12040114</span><br><span class="line"></span><br><span class="line">上锁后：</span><br><span class="line">value：10000000</span><br><span class="line">value：20000000</span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：如果没有全局变量或者只是单纯的访问全局变量，不要用锁机制</p>
<h4 id="多线程之生产者和消费者"><a href="#多线程之生产者和消费者" class="headerlink" title="多线程之生产者和消费者"></a>多线程之生产者和消费者</h4><h5 id="Lock版"><a href="#Lock版" class="headerlink" title="Lock版"></a>Lock版</h5><p>  生产者和消费者模式是多线程开发中经常见到的一种模式。生产者的线程专门]用来生产一些数据，然后存放到一个中间的变量中。消费者再从这个中间的变量中取出数据进行消费。但是因为要使用中间变量，中间变量经常是一些全局变量，因此需要使用锁来保证数据完整性。<br>  例示代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">gMoney = <span class="number">1000</span></span><br><span class="line">gLock = threading.Lock()  <span class="comment"># 生产者消费者共用一把锁</span></span><br><span class="line">gTotalTimes = <span class="number">10</span>   <span class="comment"># 生产者总生产10次</span></span><br><span class="line">gTimes = <span class="number">0</span>  <span class="comment"># 记录生产者生产次数</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Producer</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> gMoney  <span class="comment"># 改变全局变量的值</span></span><br><span class="line">        <span class="keyword">global</span> gTimes</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            money = random.randint(<span class="number">100</span>,<span class="number">1000</span>)  <span class="comment"># 需要导入random包</span></span><br><span class="line">            gLock.acquire()  <span class="comment"># 获取这把锁</span></span><br><span class="line">            <span class="keyword">if</span> gTimes &gt;= gTotalTimes:  <span class="comment"># 次数达到10次</span></span><br><span class="line">                gLock.release() <span class="comment"># 跳出循环，也要记得开锁</span></span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            gMoney += money</span><br><span class="line">            print(<span class="string">'%s生产了%d元钱，剩余%d元钱'</span>%(threading.current_thread(),money,gMoney))</span><br><span class="line">            gTimes += <span class="number">1</span></span><br><span class="line">            gLock.release()</span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Consumer</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> gMoney</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            money = random.randint(<span class="number">100</span>,<span class="number">1000</span>)</span><br><span class="line">            gLock.acquire()</span><br><span class="line">            <span class="keyword">if</span> gMoney &gt;= money:</span><br><span class="line">                gMoney -= money</span><br><span class="line">                print(<span class="string">'%s消费者消费了%d元钱，剩余%d元钱'</span> % (threading.current_thread(),money,gMoney))</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">if</span> gTimes &gt;= gTotalTimes:</span><br><span class="line">                    gLock.release()</span><br><span class="line">                    <span class="keyword">break</span></span><br><span class="line">                print(<span class="string">'%s消费者准备消费%d元钱，剩余%d元钱，不足！'</span>%(threading.current_thread(),money,gMoney))</span><br><span class="line">            gLock.release()</span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>): <span class="comment"># 三个消费者</span></span><br><span class="line">        t = Consumer(name=<span class="string">'消费者线程%d'</span>%x) <span class="comment"># 可以直接命名</span></span><br><span class="line">        t.start()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">5</span>): <span class="comment"># 五个生产者</span></span><br><span class="line">        t = Producer(name=<span class="string">"生产者线程%d"</span>%x)</span><br><span class="line">        t.start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h5 id="Condition版"><a href="#Condition版" class="headerlink" title="Condition版"></a>Condition版</h5><p>  Lock版本的生产者与消费者模式可以正常的运行。但是存在一个不足，在消费者中，总是通过while True死循环并且上锁的方式去判断钱够不够。<strong>上锁是一个很耗费CPU资源的行为。</strong> 因此这种方式不是最好的。还有一种更好的方式便是使用threading.Condition来实现。threading. Condition可以在没有数据的时候处于阻塞等待状态。一旦有合适的数据了，还可以使用notify 相关的函数来通知其他处于等待状态的线程。这样就可以不用做一-些无用的上锁和解锁的操作。可以提高程序的性能。<br>  threading.Condition 类似threading.Lock ,可以在修改全局数据的时候进行上锁,也可以在修改完毕后进行解锁。以下将一些常用的函数做个简单的介绍：</p>
<ul>
<li>acquire :上锁。</li>
<li>release :解锁。</li>
<li>wait :将当前线程处于等待状态，并且<strong>会释放锁</strong>。可以被其他线程使用notify和notify_ all函数唤醒。被唤醒后会立马上锁，<strong>继续执行下面的代码。</strong></li>
<li>notify :通知某个正在等待的线程，默认是第1个等待的线程。<strong>需要在release之前调用。</strong></li>
<li>notify. all :通知所有正在等待的线程。 notify和notify. al1不会释放锁。<strong>并且需要在release之前调用。</strong></li>
</ul>
<p>Condition版的生产者与消费者模式示例代码如下:<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">gMoney = <span class="number">1000</span></span><br><span class="line">gCondition = threading.Condition()</span><br><span class="line">gTotalTimes = <span class="number">10</span></span><br><span class="line">gTimes = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Producer</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> gMoney</span><br><span class="line">        <span class="keyword">global</span> gTimes</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            money = random.randint(<span class="number">100</span>,<span class="number">1000</span>)</span><br><span class="line">            gCondition.acquire()</span><br><span class="line">            <span class="keyword">if</span> gTimes &gt;= gTotalTimes:</span><br><span class="line">                gCondition.release()</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            gMoney += money</span><br><span class="line">            print(<span class="string">'%s生产了%d元钱，剩余%d元钱'</span>%(threading.current_thread(),money,gMoney))</span><br><span class="line">            gTimes += <span class="number">1</span></span><br><span class="line">            gCondition.notify_all() <span class="comment"># 提醒所有等待的线程</span></span><br><span class="line">            gCondition.release()</span><br><span class="line">            time.sleep(<span class="number">0.5</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Consumer</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> gMoney</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            money = random.randint(<span class="number">100</span>,<span class="number">1000</span>)</span><br><span class="line">            gCondition.acquire()</span><br><span class="line">            <span class="keyword">while</span> gMoney &lt; money:   <span class="comment"># 被提醒不需等待后仍要排队，所以还是可能会出现生产的不够消费的情况，所以还是需要判断。</span></span><br><span class="line">                <span class="keyword">if</span> gTimes &gt;= gTotalTimes:</span><br><span class="line">                    gCondition.release() <span class="comment"># 返回整个函数之前还是要记得释放锁</span></span><br><span class="line">                    <span class="keyword">return</span>   <span class="comment"># break只能跳出最近的while循环</span></span><br><span class="line">                print(<span class="string">'%s准备消费%d元钱，剩余%d元钱，不足！'</span> % (threading.current_thread(),money,gMoney))</span><br><span class="line">                gCondition.wait()  <span class="comment"># 等待  结束等待后继续执行下面的代码</span></span><br><span class="line">            gMoney -= money</span><br><span class="line">            print(<span class="string">'%s消费了%d元钱，剩余%d元钱'</span> % (threading.current_thread(),money,gMoney))</span><br><span class="line">            gCondition.release()</span><br><span class="line">            time.sleep(<span class="number">0.5</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">3</span>):</span><br><span class="line">        t = Consumer(name=<span class="string">'消费者线程%d'</span>%x)</span><br><span class="line">        t.start()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">5</span>):</span><br><span class="line">        t = Producer(name=<span class="string">"生产者线程%d"</span>%x)</span><br><span class="line">        t.start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure></p>
<h4 id="Queue线程安全队列"><a href="#Queue线程安全队列" class="headerlink" title="Queue线程安全队列"></a>Queue线程安全队列</h4><p>  在线程中，访问一些全局变量，加锁是一个经常的过程。如果你是想把一些数据存储到某个队列中，那么Python内置了一个线程安全的模块叫做queue 模块。Python中 的queue模块中提供了同步的、线程安全的队列类，包括FIFO (先进先出)队列Queue, LIFO (后入先出)队列LifoQueue.这些队列都实现了锁原语(可以理解为原子操作，即要么不做，要么都做完) ,能够在多线程中直接使用。可以使用队列来实现线程间的同步。相关的函数如下:</p>
<ul>
<li>初始化Queue(maxsize):创建一个先进先出的队列。</li>
<li>qsize(): 返回队列的大小。</li>
<li>empty():判断队列是否为空。</li>
<li>full():判断队列是否满了。</li>
<li>get():从队列中取最后一个数据。</li>
<li>put():将一个数据放到队列中。</li>
</ul>
<p>例示代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">set_value</span><span class="params">(q)</span>:</span> <span class="comment"># 带有参数 队列q</span></span><br><span class="line">    index = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        q.put(index)</span><br><span class="line">        index += <span class="number">1</span></span><br><span class="line">        time.sleep(<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_value</span><span class="params">(q)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        print(q.get())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    q = Queue(<span class="number">4</span>)</span><br><span class="line">    t1 = threading.Thread(target=set_value,args=[q])</span><br><span class="line">    t2 = threading.Thread(target=get_value,args=[q])</span><br><span class="line"></span><br><span class="line">    t1.start()</span><br><span class="line">    t2.start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure></p>
<h4 id="GIL全局解释器锁"><a href="#GIL全局解释器锁" class="headerlink" title="GIL全局解释器锁"></a>GIL全局解释器锁</h4><p>  Python自带的解释器是CPython 。CPython 解释器的多线程实际上是一个假的多线程(在多核CPU中，只能利用一核，不能利用多核，但是cpu在不断地切换线程，给我们多线程的感觉 )。同一时刻只有一个线程在执行，为了保证同一时刻只有一个线程在执行，在CPython 解释器中有一个东西叫做GIL (GlobalIntepreter Lock) , 叫做全局解释器锁。这个解释器锁是有必要的。因为CPython解释器的内存管理不是线程安全的。当然除了CPython解释器，还有其他的解释器，有些解释器是没有GIL 锁的，见下面:</p>
<ul>
<li>Jython :用Java实现的Python解释器。不存在GIL锁。</li>
<li>IronPython :用.net 实现的Python解释器。不存在GIL锁。</li>
<li><p>PyPy: 用Python实现的Python解释器。存在GIL锁。</p>
<p>GIL虽然是一个假的多线程。<strong>但是在处理一些IO操作 (比如文件读写和网络请求)还是可以在很大程度上提高效率的。在I0操作上建议使用多线程提高效率。在一些CPU计算操作上不建议使用多线程,而建议使用多进程。</strong></p>
</li>
</ul>
<h2 id="动态网页数据抓取-AJAX"><a href="#动态网页数据抓取-AJAX" class="headerlink" title="动态网页数据抓取  AJAX"></a>动态网页数据抓取  AJAX</h2><h3 id="什么是AJAX"><a href="#什么是AJAX" class="headerlink" title="什么是AJAX"></a>什么是AJAX</h3><p>  AJAX ( Asynchronouse JavaScript And XML)异步JavaScript和XML。AJAX 是一种在<strong>无需重新加载整个网页的情况下，能够更新部分网页的技术</strong>。通过在后台与服务器进行少量数据交换，Ajax可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下，对网页的某部分进行更新。传统的网页(不使用Ajax) 如果需要更新内容，必须重载整个网页页面。因为传统的在传输数据格式方面使用的是XML 语法。因此叫做AJAX <strong>,其实现在数据交互基本上都是使用JSON。</strong>使用AJAX加载的数据，即使使用了JS,将数据渲染到了浏览器中，在（右键-&gt;查有网页源代码）还是不能看到通过ajax加载的数据，只能看到使用这个url加载的html代码。</p>
<p>  获取ajax数据的方式:</p>
<p>  1.直接分析ajax调用的接口。然后通过代码请求这个接口。<br>  2.使用Selenium+chromedriver模拟浏览器行为获取数据。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方式</th>
<th style="text-align:left">优点</th>
<th style="text-align:left">缺点</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">分析接口</td>
<td style="text-align:left">直接可以请求到数据。不需要做一些解析工作。代码量少，性能高。</td>
<td style="text-align:left">分析接口比较负责，特别是一些通过js 混淆的接口，要有一定的js功底。容易被发现是爬虫。</td>
</tr>
<tr>
<td style="text-align:left">selenium</td>
<td style="text-align:left">直接模拟浏览器的行为。浏览器能请求到的，使用selenium也能请求到。爬虫更稳定。</td>
<td style="text-align:left">代码量多。性能低。</td>
</tr>
</tbody>
</table>
<h4 id="Selenium-chromedriver获取动态数据"><a href="#Selenium-chromedriver获取动态数据" class="headerlink" title="Selenium+chromedriver获取动态数据:"></a>Selenium+chromedriver获取动态数据:</h4><p>  Selenium相当于是一个机器人。可以模拟人类在浏览器上的-些行为，自动处理浏览器上的一些行为，比如点击，填充数据，删除cookie等。Selenium最初是用来做自动化测试的，只是后来被发现可以运用在爬虫中。针对不同的浏览器有不同的driver。以下是两个浏览器及其对应的driver:</p>
<ol>
<li>Chrome的Chromedriver· : <a href="http://sites.google.com/a/chromium.org/chromedriver/downloads" target="_blank" rel="noopener">http://sites.google.com/a/chromium.org/chromedriver/downloads</a></li>
<li>Firefox的geckodriver: <a href="https://github.com/mozilla/geckodriver/releases" target="_blank" rel="noopener">https://github.com/mozilla/geckodriver/releases</a></li>
</ol>
<h5 id="安装Selenium和Firefox的geckodriver"><a href="#安装Selenium和Firefox的geckodriver" class="headerlink" title="安装Selenium和Firefox的geckodriver"></a>安装Selenium和Firefox的geckodriver</h5><p>1.安装Selenium : Selenium 有很多语言的版本，有java、ruby、 python等。 我们下载python版本的就可以了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install selenium</span><br></pre></td></tr></table></figure>
<p>2.安装geckodriver :下载完成后,放到不需要权限的纯英文目录下就可以了。</p>
<h5 id="Selenium操作"><a href="#Selenium操作" class="headerlink" title="Selenium操作"></a>Selenium操作</h5><h6 id="打开和关闭"><a href="#打开和关闭" class="headerlink" title="打开和关闭"></a>打开和关闭</h6><p>关闭页面:</p>
<ul>
<li>driver.clkse() :关闭当前页面。</li>
<li>driver.quit() :退出整个浏览器。</li>
</ul>
<p>例示代码：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.baidu.com/'</span>)</span><br><span class="line"></span><br><span class="line">print(driver.page_source) <span class="comment"># 打印网页源代码</span></span><br><span class="line"></span><br><span class="line">time.sleep(<span class="number">5</span>)</span><br><span class="line"><span class="comment"># driver.close()</span></span><br><span class="line">driver.quit()</span><br></pre></td></tr></table></figure></p>
<h6 id="定位元素"><a href="#定位元素" class="headerlink" title="定位元素"></a>定位元素</h6><ol>
<li>find_ element_ by _id :根据id来查找某个元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTag = driver. find_ element_ by_ id(&apos;su&apos;)</span><br><span class="line">submitTagl = driver. find_ element(By.ID, &apos;su&apos;)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>find_ element_by_class_name :根据类名查找元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTagI driiver. find_ element by_ class_ name(&apos;su&apos;)</span><br><span class="line">submitTag1元driver . find_ element(By.CLASS_ NAME, &apos;su&apos;)</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>find _element _by _name :根据name属性的值来查找元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTag = driver. find_ element_by_name( &apos; email&apos; )</span><br><span class="line">submitTagl = driver. find_ element(By.NAME,&apos;email&apos;)</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>find element_ by_ tag_ name :根据标签名来查找元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTag = driver.find_ element _by_tag. name(&apos;div&apos;)</span><br><span class="line">submitTag1 = driver.find_ element(By.TAG_ NAME,&apos;div&apos;)</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>find_ element _by_xpath :根据xpath语法来获取元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTag = driver.find_ element_ by_xpath(&apos;//div&apos;)</span><br><span class="line">submitTag1 = driver.find_ element(By. XPATH, &apos;//div&apos;)</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>find element_ by_ .css_ selector :根据css选择器选择元素。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">submitTag。driver. find_ element_ by_ Css_ selector(&apos;//div&apos;)</span><br><span class="line">submitTag1。driver . find_ element(By.CSS_ SELECTOR,&apos;//div&apos;)</span><br></pre></td></tr></table></figure>
<h6 id="操作表单元素"><a href="#操作表单元素" class="headerlink" title="操作表单元素"></a>操作表单元素</h6><ol>
<li>操作输入框: 分为两步。第一步:找到这个元素。第二步:使用send, _keys(value) ,将数据填充进去。示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">inputTag = driver. find element_ by_id(<span class="string">'kw'</span> )</span><br><span class="line">inputTag.send.keys(<span class="string">'python'</span>)</span><br></pre></td></tr></table></figure>
<p>  使用Clear方法可以清除输入框中的内容。示例代码如下:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">InputTag. clear()</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>操作checkbox:因为要选中checkbox 标签，在网页中是通过鼠标点击的。因此想要选中checkbox 标签，那么先选中这个标签，然后执行click事件。示例代码如下: </li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rememberTag = driver.find element_by_name(&quot;rememberMe&quot;)</span><br><span class="line">rememberTag.click()</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>选择select: select元素不能直接点击。因为点击后还需要选中元素。这时候selenium就专门为select标签提供了一个类selenium. webdriver . suport.ui .Select。将获取到的元素当成参数传到这个类中，创建这个对象。以后就可以使用这个对象进行选择了。示例代码如下:</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">from selenium. webdriver. support.ui import Select</span><br><span class="line"></span><br><span class="line">#选中这个标签，然后使川Select创建对象</span><br><span class="line">selectTag = Select(driver.find_ element_by_ name( &quot;jumpNenu&quot; ))</span><br><span class="line"></span><br><span class="line"># 1. 根据索引选择</span><br><span class="line">selectTag.select_ by_ index(1)</span><br><span class="line"></span><br><span class="line"># 2. 根据值选择 </span><br><span class="line">selectTag.select_by_ value(&quot;http://ww.95yueba.com&quot;)</span><br><span class="line"></span><br><span class="line"># 3.根据可视的文本选择</span><br><span class="line">selectTag.select_ by_visible_text(&quot;95秀客户蹦&quot;)</span><br><span class="line"></span><br><span class="line">#取消选中所有选项</span><br><span class="line">selectTag.deselect_all()</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>操作按钮:操作按鈕有很多种方式。比如単击、右击、双去等。这里讲一个最常用的。就是点击。直接調用click函数就可以了。示例代码如下:</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">inputTag = driver.find_element_by_id(&apos;su&apos;)</span><br><span class="line">inputTag.click()</span><br></pre></td></tr></table></figure>
<h6 id="行为链"><a href="#行为链" class="headerlink" title="行为链"></a>行为链</h6><p>  有时候在页面中的操作可能要有很多步，那么这时候可以使用鼠标行为链类ActionChains来完成。比如现在要将鼠标移动到某个元素上并执行点击事件。那么示例代码如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.action_chains <span class="keyword">import</span> ActionChains</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\ProgramApp\chromedriver\chromedriver.exe"</span></span><br><span class="line">driver = webdriver.Chrome(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.baidu.com/'</span>)</span><br><span class="line"></span><br><span class="line">inputTag = driver.find element_by_id(<span class="string">'kw'</span>)</span><br><span class="line">submitTag = driver.find_ element_by_id(<span class="string">'su'</span>)</span><br><span class="line"></span><br><span class="line">actions = ActionChains(driver) <span class="comment"># 行为对象</span></span><br><span class="line">actions.move_to_element(inputTag) <span class="comment"># 移动到输入框</span></span><br><span class="line">actions.send_keys_to_element(inputTag,<span class="string">'python'</span>) <span class="comment"># 输入值</span></span><br><span class="line">actions .move_to_element(submitTag) <span class="comment"># 移动到提交按钮</span></span><br><span class="line">actions.click(submitTag) <span class="comment"># 点击提交按钮</span></span><br><span class="line">actions.perform() <span class="comment"># 整个行为表演一遍</span></span><br></pre></td></tr></table></figure>
<p>  还有更多的鼠标相关的操作。</p>
<ul>
<li>click and_hold(element): 点击但不松开鼠标。</li>
<li>context_click(element): 右键点击.</li>
<li>double_click(element): 双击。</li>
</ul>
<p>更多方法请参考: <a href="http://selenium-python.readthedocs.io/api.html" target="_blank" rel="noopener">更多方法请参考</a></p>
<h6 id="selenium-操作cookie"><a href="#selenium-操作cookie" class="headerlink" title="selenium 操作cookie"></a>selenium 操作cookie</h6><p>Cookie操作:<br>1.获取所有的cookie :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">for cookie in driver.get_cookies():</span><br><span class="line">print(cookie)</span><br></pre></td></tr></table></figure>
<p>2.根据cookie的key获取value:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">value.driver.get_cookie(key)</span><br></pre></td></tr></table></figure>
<p>3.删除所有的cookie:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">driver.delete_all_cookies()</span><br></pre></td></tr></table></figure>
<p>4.删除某个cookie :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">driver.delete_cookie(key)</span><br></pre></td></tr></table></figure>
<p>例示代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.action_chains <span class="keyword">import</span> ActionChains</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.baidu.com/'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> cookie <span class="keyword">in</span> driver.get_cookies():<span class="comment"># 获取所有的cookies</span></span><br><span class="line">    print(cookie)</span><br><span class="line"></span><br><span class="line">print(<span class="string">'='</span>*<span class="number">30</span>)</span><br><span class="line"></span><br><span class="line">print(driver.get_cookie(<span class="string">"PSTM"</span>))<span class="comment"># 根据cookie的key获取value</span></span><br><span class="line"></span><br><span class="line">driver.delete_cookie(<span class="string">"PSTM"</span>) <span class="comment">#根据cookie名删除</span></span><br><span class="line">print(<span class="string">'='</span>*<span class="number">30</span>)</span><br><span class="line">print(driver.get_cookie(<span class="string">'PSTM'</span>))</span><br><span class="line">driver.delete_all_cookies()<span class="comment"># 删除所有的·cookie</span></span><br></pre></td></tr></table></figure>
<h6 id="页面等待"><a href="#页面等待" class="headerlink" title="页面等待:"></a>页面等待:</h6><p>  现在的网页越来越多采用了Ajax 技术，这样程序便不能确定何时某个元素完全加载出来了。<strong>如果实际页面等待时间过长导致某个dom元素还没出来，但是你的代码直接使用了这个WebElement,那么就会抛出NullPointer的异常。</strong>为了解决这个问题。所以Selenium提供了两种等待方式: 一种是隐式等待、一种是显式等待。</p>
<ol>
<li>隐式等待:调用driver.implicitly_wait。那么在获取不可用的元素之前，会先等待传入的时间。示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line"></span><br><span class="line">driver.implicitly_wait(<span class="number">10</span>)</span><br><span class="line">driver.get(<span class="string">'https://www.douban.com/'</span>)</span><br><span class="line">driver.find_element_by_id(<span class="string">"dsjkafhaafh"</span>)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>显示等待:显示等待是表明某个条件成立后才执行获取元素的操作。也可以在等待的时候指定一个最大的时间，如果还没超过这个时间就加载出来了就不再等待，如果超过这个时间那么就抛出一个异常。显示等待应该使用selenium. webdriver. support.excepted_conditions 期望的条件和selenium.webdriver.support .ui .WebDriverWait来配合完成。示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment"># 显式等待</span></span><br><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support.ui <span class="keyword">import</span> WebDriverWait <span class="comment"># 显示等待</span></span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.support <span class="keyword">import</span> expected_conditions <span class="keyword">as</span> EC</span><br><span class="line"><span class="keyword">from</span> selenium.webdriver.common.by <span class="keyword">import</span> By</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.douban.com/'</span>)</span><br><span class="line"></span><br><span class="line">element = WebDriverWait(driver,<span class="number">10</span>).until(</span><br><span class="line">    EC.presence_of_element_located((By.ID,<span class="string">'fdgfst34'</span>))</span><br><span class="line">)</span><br><span class="line">print(element)</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>一些其他的等待条件:</li>
</ol>
<ul>
<li>presence_of_element_located: 某个元素已经加载完毕了。</li>
<li>presence_of_all_emement_located: 网页中所有满足条件的元素都载完毕了。</li>
<li>element_to_be_cliable:某个元素是可以点击了。<br>更多条件请参考:<a href="http://selenium-python.readthedocs.io/waits.html" target="_blank" rel="noopener">更多条件请参考</a></li>
</ul>
<h6 id="切换页面"><a href="#切换页面" class="headerlink" title="切换页面"></a>切换页面</h6><p>  有时候窗口中有很多子tab页面。这时候肯定是需要进行切换的。selenium 提供了一个叫做switch_to.window 来进行切换，具体切换到哪个页面，可以从driver.window_handles 中找到。示例代码如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.baidu.com/'</span>)</span><br><span class="line"></span><br><span class="line">print(driver.current_url) <span class="comment"># 打印当前url</span></span><br><span class="line"><span class="comment"># print(driver.page_source)# 打印当前页面代码</span></span><br><span class="line">js = <span class="string">"window.open('https://www.douban.com/')"</span></span><br><span class="line">driver.execute_script(js)<span class="comment"># 打开新的页面</span></span><br><span class="line">print(driver.current_window_handle)</span><br><span class="line">handles = driver.window_handles</span><br><span class="line">print(handles)</span><br><span class="line">time.sleep(<span class="number">2</span>) <span class="comment"># 设置一个睡眠时间否则会，因为执行速度太快还没加载完第二个页面就直接跳转</span></span><br><span class="line">driver.switch_to.window(handles[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">print(driver.current_url)</span><br><span class="line"><span class="comment"># print(driver.page_source)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 虽然在窗口中切换到了新的页面。但是driver中还没有切换。</span></span><br><span class="line"><span class="comment"># 如果想要在代码中切换到新的页面，并且做一些爬虫。</span></span><br><span class="line"><span class="comment"># 那么应该使用driver.switch_to_window来切换到指定的窗口</span></span><br><span class="line"><span class="comment"># 从driver.window_handlers中取出具体第几个窗口</span></span><br><span class="line"><span class="comment"># driver.window_handlers是一个列表，里面装的都是窗口句柄。</span></span><br><span class="line"><span class="comment"># 他会按照打开页面的顺序来存储窗口的句柄。</span></span><br></pre></td></tr></table></figure>
<p>运行结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">https://www.baidu.com/</span><br><span class="line">6442450945</span><br><span class="line">[&apos;6442450945&apos;, &apos;6442450949&apos;]</span><br><span class="line">https://www.douban.com/</span><br></pre></td></tr></table></figure></p>
<h6 id="selenium设置代理ip"><a href="#selenium设置代理ip" class="headerlink" title="selenium设置代理ip:"></a>selenium设置代理ip:</h6><p>  有时候频繁爬取一些网页。服务器发现你是爬虫后会封掉你的ip地址。这时候我们可以更改代理ip。更改代理ip,不同的浏览器有不同的实现方式。这里以Chrome 浏览器为例来讲解:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"></span><br><span class="line">driver_path =<span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">options = webdriver.FirefoxOptions()</span><br><span class="line">options.add_argument(<span class="string">"--proxy-server=http://116.208.55.75:9999"</span>)</span><br><span class="line"></span><br><span class="line">driver = webdriver.Firefox(firefox_options=options,executable_path=driver_path)</span><br><span class="line"></span><br><span class="line">driver.get(<span class="string">"https://www.whatismyip.com/"</span>)</span><br></pre></td></tr></table></figure>
<p>结果说明：执行该代码发现ip还是本机ip（笑哭），找了很久的解决方案也没找到。。。。</p>
<h6 id="WebElement元素"><a href="#WebElement元素" class="headerlink" title="WebElement元素:"></a>WebElement元素:</h6><p>from selenium . webdriver.remote.webelement import WebElement 类是每个获取出来的元素的所属类。有一些常用的属性:</p>
<ol>
<li>get_attribute:这个标签的某个属性的值。</li>
<li>screentshot:获取当前页面的截图。这个方法只能在driver上使用。</li>
</ol>
<p><strong>driver的对象类，也是继承自WebElement 。</strong><br>更多请阅读相关源代码。（ctrl + b）</p>
<p>例示代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> selenium <span class="keyword">import</span> webdriver</span><br><span class="line"></span><br><span class="line">driver_path = <span class="string">r"D:\FireFoxDriver\geckodriver.exe"</span></span><br><span class="line">driver = webdriver.Firefox(executable_path=driver_path)</span><br><span class="line">driver.get(<span class="string">'https://www.baidu.com/'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">submitBtn = driver.find_element_by_id(<span class="string">'su'</span>)</span><br><span class="line">print(type(submitBtn))</span><br><span class="line"></span><br><span class="line">print(submitBtn.get_attribute(<span class="string">"value"</span>))</span><br><span class="line">driver.save_screenshot(<span class="string">'baidu.png'</span>) <span class="comment"># 当前路径会生成当前网页截屏文件</span></span><br></pre></td></tr></table></figure>
<p>运行结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;class &apos;selenium.webdriver.firefox.webelement.FirefoxWebElement&apos;&gt;</span><br><span class="line">百度一下</span><br></pre></td></tr></table></figure></p>
<h2 id="Tesseract-图片识别"><a href="#Tesseract-图片识别" class="headerlink" title="Tesseract 图片识别"></a>Tesseract 图片识别</h2><h3 id="安装及配置"><a href="#安装及配置" class="headerlink" title="安装及配置"></a>安装及配置</h3><ol>
<li>安装<br>tesseract下载地址：<a href="https://digi.bib.uni-mannheim.de/tesseract/" target="_blank" rel="noopener">tesseract下载地址</a></li>
</ol>
<p>我这里下载的是 tesseract-ocr-setup-3.05.02-20180621.exe<br>双击安装，然后在如图所示Additional Language data项选择你要识别图片里包含的语言：一般勾选英语、简单汉语和Math，默认c盘路径不要更改。</p>
<p><img src="/image/tesseract_install.png" alt></p>
<ol start="2">
<li>配置环境变量<br>此电脑-高级设置-环境配置-系统变量：<br>① 新建，变量名TESSDATA_PREFIX ，变量值：C:\Program Files (x86)\Tesseract-OCR\tessdata。<br>② 想要在cmd下能够使用tesseract命令，那么需要把tesseract.exe所在的目录放到PATH 环境变量中，找到变量名为path，新添加路径：C:\Program Files (x86)\Tesseract-OCR。</li>
</ol>
<ul>
<li><p>配置完成后在命令行输入tesseract -v验证是否配置成功</p>
</li>
<li><p>用命令tesseract –list-langs来查看Tesseract-OCR支持语言。</p>
</li>
</ul>
<h3 id="在终端下识别图片"><a href="#在终端下识别图片" class="headerlink" title="在终端下识别图片"></a>在终端下识别图片</h3><p>  cmd命令cd到你要识别图片的路径下,输入命令</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"> tesseract 图片路径 文件路径</span><br><span class="line">eg:  tesseract a.png D:\python\a</span><br><span class="line"></span><br><span class="line">那么就会识别出a.png中的图片，并且把文字写入到a.txt 中。如果不想写入文件,直接想显示在终端，那么不要加文件名就可以了。</span><br></pre></td></tr></table></figure>
<h3 id="python代码识别图片"><a href="#python代码识别图片" class="headerlink" title="python代码识别图片"></a>python代码识别图片</h3><p>  在Python代码中操作tesseract 。需要安装-个库， 叫做pytesseract 。通过pip的方式即可安装:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install pytesseract</span><br></pre></td></tr></table></figure>
<p>并且，需要读取图片，需要借助一个第三方库叫做PIL 。通过pip  list看下是否安装。如果没有安装，通过pip的方式安装:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install PIL</span><br></pre></td></tr></table></figure>
<p>例示代码：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> pytesseract</span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</span><br><span class="line"></span><br><span class="line"><span class="comment"># 指定 tesseract.exe所在的路径</span></span><br><span class="line">pytesseract.pytesseract.tesseract_cmd = <span class="string">r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 打开图片</span></span><br><span class="line">image = Image.open(<span class="string">'a.png'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 调用image_to_string将图片转化为文字。</span></span><br><span class="line">text = pytesseract.image_to_string(image,lang=<span class="string">'eng'</span>)</span><br><span class="line">print(text)</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多线程/" rel="tag"># 多线程</a>
          
            <a href="/tags/ajax/" rel="tag"># ajax</a>
          
            <a href="/tags/selenium/" rel="tag"># selenium</a>
          
            <a href="/tags/tesseract图片识别/" rel="tag"># tesseract图片识别</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/13/Python爬虫（3）/" rel="next" title="Python爬虫（3）">
                <i class="fa fa-chevron-left"></i> Python爬虫（3）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/05/Python爬虫（5）/" rel="prev" title="Python爬虫（5）">
                Python爬虫（5） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#python爬虫进阶"><span class="nav-number">1.</span> <span class="nav-text">python爬虫进阶</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#多线程"><span class="nav-number">1.1.</span> <span class="nav-text">多线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#多线程介绍"><span class="nav-number">1.1.1.</span> <span class="nav-text">多线程介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#threading模块"><span class="nav-number">1.1.2.</span> <span class="nav-text">threading模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Thread类"><span class="nav-number">1.1.3.</span> <span class="nav-text">Thread类:</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#多线程共享全局变量问题及解决办法：锁机制"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">多线程共享全局变量问题及解决办法：锁机制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多线程之生产者和消费者"><span class="nav-number">1.1.3.2.</span> <span class="nav-text">多线程之生产者和消费者</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Lock版"><span class="nav-number">1.1.3.2.1.</span> <span class="nav-text">Lock版</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Condition版"><span class="nav-number">1.1.3.2.2.</span> <span class="nav-text">Condition版</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Queue线程安全队列"><span class="nav-number">1.1.3.3.</span> <span class="nav-text">Queue线程安全队列</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#GIL全局解释器锁"><span class="nav-number">1.1.3.4.</span> <span class="nav-text">GIL全局解释器锁</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态网页数据抓取-AJAX"><span class="nav-number">1.2.</span> <span class="nav-text">动态网页数据抓取  AJAX</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是AJAX"><span class="nav-number">1.2.1.</span> <span class="nav-text">什么是AJAX</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Selenium-chromedriver获取动态数据"><span class="nav-number">1.2.1.1.</span> <span class="nav-text">Selenium+chromedriver获取动态数据:</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#安装Selenium和Firefox的geckodriver"><span class="nav-number">1.2.1.1.1.</span> <span class="nav-text">安装Selenium和Firefox的geckodriver</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Selenium操作"><span class="nav-number">1.2.1.1.2.</span> <span class="nav-text">Selenium操作</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#打开和关闭"><span class="nav-number">1.2.1.1.2.1.</span> <span class="nav-text">打开和关闭</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#定位元素"><span class="nav-number">1.2.1.1.2.2.</span> <span class="nav-text">定位元素</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#操作表单元素"><span class="nav-number">1.2.1.1.2.3.</span> <span class="nav-text">操作表单元素</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#行为链"><span class="nav-number">1.2.1.1.2.4.</span> <span class="nav-text">行为链</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#selenium-操作cookie"><span class="nav-number">1.2.1.1.2.5.</span> <span class="nav-text">selenium 操作cookie</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#页面等待"><span class="nav-number">1.2.1.1.2.6.</span> <span class="nav-text">页面等待:</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#切换页面"><span class="nav-number">1.2.1.1.2.7.</span> <span class="nav-text">切换页面</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#selenium设置代理ip"><span class="nav-number">1.2.1.1.2.8.</span> <span class="nav-text">selenium设置代理ip:</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#WebElement元素"><span class="nav-number">1.2.1.1.2.9.</span> <span class="nav-text">WebElement元素:</span></a></li></ol></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Tesseract-图片识别"><span class="nav-number">1.3.</span> <span class="nav-text">Tesseract 图片识别</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装及配置"><span class="nav-number">1.3.1.</span> <span class="nav-text">安装及配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#在终端下识别图片"><span class="nav-number">1.3.2.</span> <span class="nav-text">在终端下识别图片</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#python代码识别图片"><span class="nav-number">1.3.3.</span> <span class="nav-text">python代码识别图片</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
